package com.coolingme.demo.passport.adapterv2;

import com.coolingme.demo.passport.ResultMsg;
import com.coolingme.demo.passport.adapterv2.adpters.ILoginAdapter;
import com.coolingme.demo.passport.adapterv2.adpters.LoginForPhoneAdapter;
import com.coolingme.demo.passport.adapterv2.adpters.LoginForQqAdapter;
import com.coolingme.demo.passport.adapterv2.adpters.LoginForTokenAdapter;

/**
 * 第三方登录适配器，对其他适配的调用
 *
 * @author wangyue
 * @date 2020-09-20 13:58
 */
public class PassportForThirdAdapter implements IPassportService {

    @Override
    public ResultMsg loginForQQ(String openId) {
        System.out.println("loginForQQ");
        return processLogin(openId, LoginForQqAdapter.class);
    }

    @Override
    public ResultMsg loginForToken(String token) {
        System.out.println("loginForToken");
        return processLogin(token, LoginForTokenAdapter.class);
    }

    @Override
    public ResultMsg loginForPhone(String phone, String code) {
        System.out.println("loginForPhone");
        // 将code放到缓存中
        return processLogin(phone, LoginForPhoneAdapter.class);
    }

    /**
     * 根据不同的适配器类调用不同的登录方式
     * 如果有多个参数，可以修改为object[]
     *
     * @param id    登录标识
     * @param clazz 适配器类对象
     * @return ResultMsg
     */
    private ResultMsg processLogin(String id, Class<? extends ILoginAdapter> clazz) {
        try {
            ILoginAdapter adapter = clazz.newInstance();
            if (adapter.support(adapter)) {
                return adapter.login(id, adapter);
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }


}
